/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.controller;

import com.minierp.dao.CodeRuleDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.ProductDao;
import com.minierp.dao.ProductTypeDao;
import com.minierp.dao.SerialNumberDao;
import com.minierp.dao.StockDao;
import com.minierp.err.PermissionDennyException;
import com.minierp.helper.EncCommonHelper;
import com.minierp.helper.PageHelper;
import com.minierp.model.CodeRule;
import com.minierp.model.Product;
import com.minierp.model.ProductType;
import com.minierp.model.Stock;
import com.minierp.view.ProductListExcelView;
import com.minierp.view.ProductListPDExcelView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class ProductMACtr extends MultiActionController {
	private ProductDao productDao;
	private ProductTypeDao productTypeDao;
	private StockDao stockDao;
	private CodeRuleDao codeRuleDao;
	private SerialNumberDao serialNumberDao;
	private IdGenerator idGenerator;
	private String mainView;
	private String listView;
	private String mainForSelectView;
	private String listForSelectView;
	private String listForMultiSelectView;
	private String changeTypeFormView;
	private String uploadFormView;

	public CodeRuleDao getCodeRuleDao() {
		return this.codeRuleDao;
	}

	public void setCodeRuleDao(CodeRuleDao codeRuleDao) {
		this.codeRuleDao = codeRuleDao;
	}

	public SerialNumberDao getSerialNumberDao() {
		return this.serialNumberDao;
	}

	public void setSerialNumberDao(SerialNumberDao serialNumberDao) {
		this.serialNumberDao = serialNumberDao;
	}

	public IdGenerator getIdGenerator() {
		return this.idGenerator;
	}

	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	public String getUploadFormView() {
		return this.uploadFormView;
	}

	public void setUploadFormView(String uploadFormView) {
		this.uploadFormView = uploadFormView;
	}

	public StockDao getStockDao() {
		return this.stockDao;
	}

	public void setStockDao(StockDao stockDao) {
		this.stockDao = stockDao;
	}

	public String getChangeTypeFormView() {
		return this.changeTypeFormView;
	}

	public void setChangeTypeFormView(String changeTypeFormView) {
		this.changeTypeFormView = changeTypeFormView;
	}

	public ModelAndView handleMain(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (!EncCommonHelper.checkPrivilege(request, "BASE_PROD")) {
			throw new PermissionDennyException("Permission Denny");
		} else {
			ModelAndView mv = new ModelAndView(this.mainView);
			return mv;
		}
	}

	public ModelAndView handleList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (!EncCommonHelper.checkPrivilege(request, "BASE_PROD")) {
			throw new PermissionDennyException("Permission Denny");
		} else {
			String productTypeId = request.getParameter("type_id");
			String searchKey = request.getParameter("search_key");
			String searchAll = request.getParameter("search_all");
			String contentType = request.getParameter("content_type");
			String expoType = request.getParameter("expo_type");
			if (productTypeId == null || productTypeId.equals("")) {
				searchAll = "1";
			}

			List list;
			if (searchAll != null && searchAll.equals("1")) {
				list = this.productDao.getList(0L, searchKey, true, false, "",
						0L);
			} else {
				list = this.productDao.getList(Long.parseLong(productTypeId),
						searchKey, true, false, "", 0L);
			}

			if (contentType != null && contentType.equals("EXCEL")) {
				HashMap mv1;
				if (expoType != null && expoType.equals("PD")) {
					mv1 = new HashMap();
					mv1.put("list", list);
					ProductListPDExcelView v1 = new ProductListPDExcelView();
					return new ModelAndView(v1, mv1);
				} else {
					mv1 = new HashMap();
					mv1.put("list", list);
					ProductListExcelView v = new ProductListExcelView();
					return new ModelAndView(v, mv1);
				}
			} else {
				ModelAndView mv = new ModelAndView(this.listView);
				if (productTypeId != null && !productTypeId.equals("")) {
					mv.addObject(
							"productType",
							this.productTypeDao.get(ProductType.class,
									Long.parseLong(productTypeId)));
				}

				mv.addObject("productList", list);
				mv.addObject("typeId", productTypeId);
				mv.addObject("searchKey", searchKey);
				mv.addObject("searchAll", searchAll);
				return mv;
			}
		}
	}

	public ModelAndView handleDelete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String retUrl = request.getParameter("from_url");
		ModelAndView mv = new ModelAndView("redirect:" + retUrl);
		String id = request.getParameter("id");
		if (this.stockDao.isProductHasStock(Long.parseLong(id))) {
			EncCommonHelper.setAlertMessage(request, "有库存存在，不能删除！");
		} else {
			Product p = (Product) this.productDao.get(Product.class,
					Long.parseLong(id));
			if (p != null) {
				p.setEnabled("N");
				this.productDao.update(p);
			}

			EncCommonHelper.setAlertMessage(request, "删除成功！");
		}

		return mv;
	}

	public ModelAndView handleMainForSelect(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(this.mainForSelectView);
		mv.addObject("type", request.getParameter("type"));
		mv.addObject("stock", request.getParameter("stock"));
		mv.addObject("stoId", request.getParameter("sto_id"));
		return mv;
	}

	public ModelAndView handleListForSelect(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String type = request.getParameter("type");
		String stock = request.getParameter("stock");
		String stoId = request.getParameter("sto_id");
		String productTypeId = request.getParameter("type_id");
		String searchKey = request.getParameter("search_key");
		String searchAll = request.getParameter("search_all");
		String stocType = request.getParameter("stoc_type");
		String id = request.getParameter("id");
		ModelAndView mv;
		if (type != null && type.equals("MULTI")) {
			mv = new ModelAndView(this.listForMultiSelectView);
		} else {
			mv = new ModelAndView(this.listForSelectView);
		}

		boolean stockFlag = false;
		long storehouseId = 0L;
		if (stock != null && stock.equals("Y")) {
			stockFlag = true;
			storehouseId = Long.parseLong(stoId);
		}

		if (id != null && !id.equals("")) {
			ArrayList list1 = new ArrayList();
			Product p = (Product) this.productDao.get(Product.class,
					Long.parseLong(id));
			if (p != null) {
				ProductType pt = (ProductType) this.productTypeDao.get(
						ProductType.class, p.getProductTypeId());
				Object[] objs = new Object[]{Long.valueOf(p.getId()),
						p.getProductCode(), p.getProductName(), p.getUnit(),
						p.getAttachFile(), Long.valueOf(p.getProductTypeId()),
						p.getMark(), pt.getTypeName(), "0"};
				list1.add(objs);
				mv.addObject("typeId", String.valueOf(p.getProductTypeId()));
				mv.addObject("productType", pt);
			}

			mv.addObject("productList", list1);
			mv.addObject("id", id);
		} else {
			if (productTypeId != null && !productTypeId.equals("")) {
				mv.addObject(
						"productType",
						this.productTypeDao.get(ProductType.class,
								Long.parseLong(productTypeId)));
			} else {
				searchAll = "1";
			}

			List list;
			if (searchAll != null && searchAll.equals("1")) {
				list = this.productDao.getList(0L, searchKey, true, stockFlag,
						stocType, storehouseId);
			} else {
				list = this.productDao.getList(Long.parseLong(productTypeId),
						searchKey, true, stockFlag, stocType, storehouseId);
			}

			mv.addObject("productList", list);
			mv.addObject("typeId", productTypeId);
			mv.addObject("searchKey", searchKey);
			mv.addObject("searchAll", searchAll);
			mv.addObject("stocType", stocType);
			mv.addObject("stock", stock);
			mv.addObject("stoId", stoId);
			mv.addObject("type", type);
		}

		return mv;
	}

	public ModelAndView handleChangeTypeForm(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(this.changeTypeFormView);
		mv.addObject("idStr", request.getParameter("id_str"));
		mv.addObject("productTypeList", this.productTypeDao.getList(true));
		return mv;
	}

	public ModelAndView handleChangeType(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String typeId = request.getParameter("type_id");
		String idStr = request.getParameter("id_str");
		String[] ids = idStr.split(";");
		long[] idArr = new long[ids.length];

		for (int mv = 0; mv < ids.length; ++mv) {
			idArr[mv] = Long.parseLong(ids[mv]);
		}

		this.productDao.update(idArr, Long.parseLong(typeId));
		ModelAndView arg7 = new ModelAndView(
				"redirect:/ModalDialogSuccess.ihtm");
		arg7.addObject("returnValue", String.valueOf(ids.length));
		EncCommonHelper.setAlertMessage(request, "修改保存成功！");
		return arg7;
	}

	public ModelAndView handleGetProduct(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String proCode = request.getParameter("pro_code");
		Product p = this.productDao.get(proCode, true);
		long id = 0L;
		String code = "";
		String name = "";
		String unit = "";
		if (p != null) {
			id = p.getId();
			code = p.getProductCode();
			name = p.getProductName();
			unit = p.getUnit();
		}

		Document doc = DocumentHelper.createDocument();
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		Element root = doc.addElement("body");
		Element posiCount = root.addElement("pro_id");
		posiCount.setText(String.valueOf(id));
		Element previewIndex = root.addElement("pro_code");
		previewIndex.setText(code);
		Element pageIndex = root.addElement("pro_name");
		pageIndex.setText(name);
		Element pageCount = root.addElement("unit");
		pageCount.setText(unit);
		response.setContentType("text/xml");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		ServletOutputStream out = response.getOutputStream();
		XMLWriter output = new XMLWriter(out, format);
		output.write(doc);
		out.flush();
		out.close();
		return null;
	}

	public ModelAndView handleGetExistingProduct(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		long storehouseId = Long.parseLong(request
				.getParameter("storehouse_id"));
		List list = this.productDao.getExisting(storehouseId);
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("body");
		long id = 0L;
		String code = "";
		String name = "";
		String unit = "";
		BigDecimal amount = null;
		Product p = null;
		Stock s = null;

		for (int format = 0; format < list.size(); ++format) {
			Object[] out = (Object[]) list.get(format);
			p = (Product) out[0];
			s = (Stock) out[1];
			if (p != null) {
				id = p.getId();
				code = p.getProductCode();
				name = p.getProductName();
				unit = p.getUnit();
				amount = s.getAmount();
			}

			Element output = root.addElement("pro");
			Element proId = output.addElement("pro_id");
			proId.setText(String.valueOf(id));
			Element proCode = output.addElement("pro_code");
			proCode.setText(code);
			Element proName = output.addElement("pro_name");
			proName.setText(name);
			Element proUnit = output.addElement("pro_unit");
			proUnit.setText(unit);
			Element proAmount = output.addElement("pro_amount");
			proAmount.setText(amount.toString());
		}

		response.setContentType("text/xml");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		OutputFormat arg23 = OutputFormat.createPrettyPrint();
		arg23.setEncoding("utf-8");
		ServletOutputStream arg24 = response.getOutputStream();
		XMLWriter arg25 = new XMLWriter(arg24, arg23);
		arg25.write(doc);
		arg24.flush();
		arg24.close();
		return null;
	}

	public ModelAndView handleUploadForm(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(this.uploadFormView);
		return mv;
	}

	public ModelAndView handleImport(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String fileName = request.getParameter("file_name");
		File file = new File(this.getServletContext().getRealPath(fileName));
		String alertMsg = "";
		String typeName = "";
		String prodCode = "";
		String prodName = "";
		String unit = "";
		String mark = "";
		List ptList = this.productTypeDao.getList(true);
		CodeRule cr = this.codeRuleDao.get("PRODUCT");
		CodeRule ptCr = this.codeRuleDao.get("PRODUCT_TYPE");
		HashMap ptMap = new HashMap();
		BufferedInputStream in = null;

		try {
			in = new BufferedInputStream(new FileInputStream(file));
			HSSFWorkbook out = new HSSFWorkbook(new POIFSFileSystem(in));
			int count = 0;

			for (int str = 0; str < out.getNumberOfSheets(); ++str) {
				HSSFSheet hssfsheet = out.getSheetAt(str);

				for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); ++j) {
					HSSFRow hssfrow = hssfsheet.getRow(j);
					if (hssfrow == null) {
						break;
					}

					HSSFCell cell = hssfrow.getCell(0);
					typeName = PageHelper.getCellVal(cell, 0);
					cell = hssfrow.getCell(1);
					prodCode = PageHelper.getCellVal(cell, 25);
					cell = hssfrow.getCell(2);
					prodName = PageHelper.getCellVal(cell, 50);
					cell = hssfrow.getCell(3);
					unit = PageHelper.getCellVal(cell, 10);
					cell = hssfrow.getCell(4);
					mark = PageHelper.getCellVal(cell, 200);
					if (!typeName.equals("") || !prodCode.equals("")
							|| !prodName.equals("") || !unit.equals("")
							|| !mark.equals("")) {
						boolean dataOk = true;
						long ptId = 0L;
						String ptCode = "";
						if (typeName != null && !typeName.equals("")) {
							ProductType pt;
							for (int p = 0; p < ptList.size(); ++p) {
								pt = (ProductType) ptList.get(p);
								if (pt.getTypeName().equals(typeName)) {
									ptId = pt.getId();
									ptCode = pt.getTypeCode();
									break;
								}
							}

							ProductType arg40;
							if (ptId == 0L && ptMap.containsKey(typeName)) {
								arg40 = (ProductType) ptMap.get(typeName);
								ptId = arg40.getId();
								ptCode = arg40.getTypeCode();
							}

							if (ptId == 0L) {
								if (!ptCr.getGenerateRule().equals("MANUAL")) {
									ptId = this.idGenerator
											.getId(ProductType.class.getName());
									ptCode = PageHelper.generateCode(
											this.serialNumberDao, ptCr, "", 0L);

									for (arg40 = this.productTypeDao
											.get(ptCode); arg40 != null; arg40 = this.productTypeDao
											.get(ptCode)) {
										ptCode = PageHelper.generateCode(
												this.serialNumberDao, ptCr, "",
												0L);
									}

									pt = new ProductType();
									pt.setId(ptId);
									pt.setNameSpell(PageHelper
											.getPinYinHeadChar(typeName)
											.toUpperCase());
									pt.setParentId(0L);
									pt.setParentIdStr("");
									pt.setTypeCode(ptCode);
									pt.setTypeName(typeName);
									this.productDao.save(pt);
									ptMap.put(typeName, pt);
								} else {
									alertMsg = PageHelper.appendAlertMsg(
											alertMsg, "第" + j
													+ "行：类别的编码规则必须设置为自动产生！");
									dataOk = false;
								}
							}
						} else {
							alertMsg = PageHelper.appendAlertMsg(alertMsg, "第"
									+ j + "行：类别不能为空！");
							dataOk = false;
						}

						Product arg41;
						if (dataOk) {
							if (prodCode != null && !prodCode.equals("")) {
								arg41 = this.productDao.get(prodCode, true);
								if (arg41 != null) {
									alertMsg = PageHelper.appendAlertMsg(
											alertMsg, "第" + j + "行：材料编码已经存在！");
									dataOk = false;
								}
							} else if (!cr.getGenerateRule().equals("MANUAL")) {
								prodCode = PageHelper.generateCode(
										this.serialNumberDao, cr, ptCode, 0L);

								for (arg41 = this.productDao
										.get(prodCode, true); arg41 != null; arg41 = this.productDao
										.get(prodCode, true)) {
									prodCode = PageHelper.generateCode(
											this.serialNumberDao, cr, ptCode,
											0L);
								}
							} else {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：材料编码规则必须设置为自动产生！");
								dataOk = false;
							}
						}

						if (dataOk) {
							if (prodName != null && !prodName.equals("")) {
								arg41 = this.productDao.getByName(prodName,
										true);
								if (arg41 != null) {
									alertMsg = PageHelper.appendAlertMsg(
											alertMsg, "第" + j + "行：品名规格已经存在！");
									dataOk = false;
								}
							} else {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：品名规格不能为空！");
								dataOk = false;
							}
						}

						if (dataOk) {
							arg41 = new Product();
							arg41.setId(this.idGenerator.getId(Product.class
									.getName()));
							arg41.setMark(mark);
							arg41.setProductCode(prodCode);
							arg41.setProductName(prodName);
							arg41.setProductTypeId(ptId);
							arg41.setUnit(unit);
							arg41.setPnSpell(PageHelper.getPinYinHeadChar(
									arg41.getProductName()).toUpperCase());
							this.productDao.save(arg41);
							++count;
						}
					}
				}
			}

			String arg39 = "成功导入" + count + "行";
			if (alertMsg != null && !alertMsg.equals("")) {
				alertMsg = PageHelper.appendAlertMsg(arg39, alertMsg);
			} else {
				alertMsg = arg39;
			}
		} catch (Exception arg36) {
			alertMsg = "导入错误：" + arg36.getMessage();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception arg35) {
				;
			}

		}

		EncCommonHelper.setAlertMessage(request, alertMsg);
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		ServletOutputStream arg38 = response.getOutputStream();
		arg38.write("OK".getBytes());
		arg38.flush();
		arg38.close();
		return null;
	}

	public ProductTypeDao getProductTypeDao() {
		return this.productTypeDao;
	}

	public void setProductTypeDao(ProductTypeDao productTypeDao) {
		this.productTypeDao = productTypeDao;
	}

	public String getListView() {
		return this.listView;
	}

	public void setListView(String listView) {
		this.listView = listView;
	}

	public String getMainView() {
		return this.mainView;
	}

	public void setMainView(String mainView) {
		this.mainView = mainView;
	}

	public ProductDao getProductDao() {
		return this.productDao;
	}

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}

	public String getListForSelectView() {
		return this.listForSelectView;
	}

	public void setListForSelectView(String listForSelectView) {
		this.listForSelectView = listForSelectView;
	}

	public String getMainForSelectView() {
		return this.mainForSelectView;
	}

	public void setMainForSelectView(String mainForSelectView) {
		this.mainForSelectView = mainForSelectView;
	}

	public String getListForMultiSelectView() {
		return this.listForMultiSelectView;
	}

	public void setListForMultiSelectView(String listForMultiSelectView) {
		this.listForMultiSelectView = listForMultiSelectView;
	}
}